package com.example.arm.common.lifecycle

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner

/**
 *  author : yanghaozhang
 *  date : 2022/12/27 15:56
 *  description :
 */
typealias LifecycleCallBack = () -> Unit

typealias LifecycleWithOwnerCallBack = (LifecycleOwner) -> Unit

fun bindLifecycleObserver(owner: Any?, binder: BaseLifecycleBinder) {
    (owner as? LifecycleOwner?)?.lifecycle?.addObserver(binder)
}

fun bindLifecycleObserver(owner: Any?, binder: BaseLifecycleWithOwnerBinder) {
    (owner as? LifecycleOwner?)?.lifecycle?.addObserver(binder)
}

fun bindLifecycleObserver(owner: Any?, targetEvent: Lifecycle.Event, callBack: LifecycleCallBack) {
    (owner as? LifecycleOwner?)?.lifecycle?.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            if (event == targetEvent) {
                callBack.invoke()
            }
        }
    })
}

fun bindLifecycleObserver(owner: Any?, targetEvent: Lifecycle.Event, callBack: LifecycleWithOwnerCallBack) {
    val lifecycleOwner = owner as? LifecycleOwner?
    lifecycleOwner?.lifecycle?.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            if (event == targetEvent) {
                callBack.invoke(lifecycleOwner)
            }
        }
    })
}

fun LifecycleOwner.bindEvent(block: BaseLifecycleBlock) {
    lifecycle.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            if (event == block.transformEvent()) {
                block.invokeBlock(this@bindEvent)
            }
        }
    })
}